using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Utilities
{
    class Semaphore
    {
        private int _count = 0;

        public Semaphore(int count)
        {
            _count = count;
        }

        public void Acquire()
        {
            try
            {
                lock (this)
                {
                    if (_count <= 0)
                    {
                        Monitor.Wait(this);
                    }

                    _count--;
                    Monitor.PulseAll(this);
                }
            }
            catch (ThreadInterruptedException)
            {
                Monitor.PulseAll(this);
            }
        }

        public void Release()
        {
            try
            {
                lock (this)
                {
                    _count++;
                    Monitor.PulseAll(this);
                }
            }
            catch (ThreadInterruptedException)
            {
                Monitor.PulseAll(this);
            }
        }

        public bool TryAcquire(int timeOut)
        {
            try
            {
                lock (this)
                {
                    if (_count > 0)
                    {
                        _count--;
                        Monitor.PulseAll(this);
                        return true;
                    }
                    else
                    {
                        Monitor.Wait(this, timeOut);
                        if (_count > 0)
                        {
                            _count--;
                            Monitor.PulseAll(this);
                            return true;
                        }
                        else
                        {
                            Monitor.PulseAll(this);
                            return false;
                        }
                    }
                }
            }
            catch(ThreadInterruptedException)
            {
                throw;
            }
        }
    }
}
